﻿using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using Store.Manager.ERP.Common.Helper;
using Store.Manager.ERP.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Store.Manager.ERP.Api
{
    public static class SqlsugarExtension
    {
        public static void AddSqlsugarSetup(this IServiceCollection services)
        {
            try
            {
                string connstr = AppsettingHelper.app(["DBS", "SqlServer", "ConnStr"]);
                SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
                {
                    DbType = DbType.SqlServer,
                    ConnectionString = connstr,
                    IsAutoCloseConnection = true,
                },
                    db =>
                    {
                        //单例参数配置，所有上下文生效
                        db.Aop.OnLogExecuting = (sql, pars) =>
                        {
                            //Console.WriteLine(sql);//输出sql
                        };

                        //技巧：拿到非ORM注入对象
                        //services.GetService<注入对象>();
                    });
                services.AddSingleton<ISqlSugarClient>(sqlSugar);//这边是SqlSugarScope用AddSingleton
            }
            catch (Exception  ex) {
                // 捕获外部异常并输出错误信息
                Console.WriteLine($"An error occurred during SqlSugarScope initialization: {ex.Message}");
            }
        }
            
    }
}
